"use client"
import React, { useState } from "react"
import {
  ChevronDown,
  Plus,
  Search,
  Ellipsis,
  Tag,
  Zap,
  VectorSquare,
  Workflow,
  MessageSquareMore,
  BellElectric
} from "lucide-react"
import { Button } from "@/components/ui/button"
import {
  DropdownMenu,
  DropdownMenuCheckboxItem,
  DropdownMenuContent,
  DropdownMenuTrigger
} from "@/components/ui/dropdown-menu"
import { Input } from "@/components/ui/input"
import { Card, CardContent } from "@/components/ui/card"
import { cn } from "@/lib/utils"
import CreateNewApplicationDialog from "./components/CreateNewApplicationDialog"
import { useRouter } from "next/navigation"

const mockApps = [
  {
    id: 1,
    name: "智能客服系统",
    description: "基于AI的智能客服解决方案，提供24小时在线服务",
    tags: ["AI", "客服", "自动化"],
    category: "客户服务",
    icon: ""
  },
  {
    id: 2,
    name: "数据分析平台",
    description: "企业级数据可视化分析工具，支持多维度数据洞察",
    tags: ["数据", "分析", "可视化"],
    category: "商业智能",
    icon: ""
  },
  {
    id: 3,
    name: "内容管理系统",
    description: "现代化内容创作与发布平台，支持多用户协作",
    tags: ["内容", "CMS", "协作"],
    category: "内容管理",
    icon: ""
  },
  {
    id: 4,
    name: "电商推荐引擎",
    description: "个性化商品推荐系统，提升用户转化率",
    tags: ["电商", "推荐", "AI"],
    category: "电子商务",
    icon: ""
  },
  {
    id: 5,
    name: "图像识别工具",
    description: "基于深度学习的图像识别应用，支持多种识别场景",
    tags: ["AI", "图像", "识别"],
    category: "计算机视觉",
    icon: ""
  },
  {
    id: 6,
    name: "语音助手",
    description: "智能语音交互系统，支持多语言识别",
    tags: ["AI", "语音", "交互"],
    category: "自然语言处理",
    icon: ""
  },
  {
    id: 7,
    name: "文档翻译器",
    description: "多语言文档翻译工具，支持多种文档格式",
    tags: ["翻译", "文档", "多语言"],
    category: "语言处理",
    icon: ""
  },
  {
    id: 8,
    name: "智能日程管理",
    description: "AI驱动的日程安排和提醒系统",
    tags: ["日程", "AI", "管理"],
    category: "生产力工具",
    icon: ""
  }
]

// 预设标签
const availableTags = [
  "AI",
  "客服",
  "自动化",
  "数据",
  "分析",
  "可视化",
  "内容",
  "CMS",
  "协作",
  "电商",
  "推荐",
  "图像",
  "识别",
  "语音",
  "交互",
  "翻译",
  "文档",
  "多语言",
  "日程",
  "管理"
]

// 分类目录
const categories = [
  {
    name: "全部",
    value: "all",
    icon: <VectorSquare className="w-4 h-4" />
  },
  {
    name: "工作流",
    value: "workflow",
    icon: <Workflow className="w-4 h-4" />
  },
  {
    name: "Chatflow",
    value: "chatflow",
    icon: <MessageSquareMore className="w-4 h-4" />
  },
  {
    name: "聊天助手",
    value: "chatbot",
    icon: <MessageSquareMore className="w-4 h-4" />
  },
  {
    name: "Agent",
    value: "agent",
    icon: <BellElectric className="w-4 h-4" />
  }
]

/**
 * 工作室
 */
const AppsPage = () => {
  const router = useRouter()

  const [isCreateNewApplicationDialogOpen, setIsCreateNewApplicationDialogOpen] = useState(false)
  // 搜索词
  const [searchTerm, setSearchTerm] = useState("")
  // 选择的标签
  const [selectedTags, setSelectedTags] = useState<string[]>([])
  // 选中的分类
  const [selectedCategory, setSelectedCategory] = useState("all")

  /**
   * 跳转应用详情
   *
   * @param id 应用 id
   */
  const handleAppClick = (id: number) => {
    router.push(`/app/${id}/workflow`)
  }

  // 过滤应用
  const filteredApps = mockApps.filter((app) => {
    const matchesSearch =
      app.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      app.description.toLowerCase().includes(searchTerm.toLowerCase())
    const matchesTags = selectedTags.length === 0 || selectedTags.some((tag) => app.tags.includes(tag))
    const matchesCategory = selectedCategory === "all" || app.category === selectedCategory
    return matchesSearch && matchesTags && matchesCategory
  })

  // 切换标签选择
  const toggleTag = (tag: string) => {
    setSelectedTags((prev) => (prev.includes(tag) ? prev.filter((t) => t !== tag) : [...prev, tag]))
  }

  return (
    <div className="flex flex-col h-full">
      <div className="sticky top-0 px-8 pt-8 pb-4 bg-gray-50 dark:bg-gray-900">
        <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-4">
          {/* 分类筛选器 */}
          <div className="flex items-center">
            {categories.map((item) => (
              <Button
                key={item.value}
                variant="ghost"
                className={cn(
                  selectedCategory === item.value
                    ? "text-blue-700 font-bold bg-white shadow-md"
                    : "text-gray-500 dark:text-white hover:bg-gray-200 dark:hover:bg-gray-700"
                )}
                onClick={() => setSelectedCategory(item.value)}
              >
                {item.icon}
                <div>{item.name}</div>
              </Button>
            ))}
          </div>

          <div className="flex flex-col sm:flex-row gap-4">
            {/* 标签筛选下拉菜单 */}
            <DropdownMenu>
              <DropdownMenuTrigger asChild>
                <Button variant="outline" className="justify-between">
                  标签筛选
                  <ChevronDown className="ml-2 h-4 w-4" />
                </Button>
              </DropdownMenuTrigger>
              <DropdownMenuContent className="w-56">
                {availableTags.map((tag) => (
                  <DropdownMenuCheckboxItem
                    key={tag}
                    checked={selectedTags.includes(tag)}
                    onCheckedChange={() => toggleTag(tag)}
                  >
                    {tag}
                  </DropdownMenuCheckboxItem>
                ))}
              </DropdownMenuContent>
            </DropdownMenu>

            {/* 搜索框 */}
            <div className="relative w-full md:w-64">
              <Search className="absolute left-3 top-1/2 transform -translate-y-1/2 text-muted-foreground h-4 w-4" />
              <Input
                placeholder="搜索应用..."
                className="pl-10"
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
              />
            </div>
          </div>
        </div>
      </div>

      <div className="grid grid-cols-1 sm:grid-cols-1 md:grid-cols-2 xl:grid-cols-3 2xl:grid-cols-5 gap-4 px-8 pt-4 pb-8">
        {/* 创建应用卡片 */}
        <Card
          className="border-2 border-dashed border-primary hover:border-solid hover:shadow-md transition-all cursor-pointer"
          onClick={() => setIsCreateNewApplicationDialogOpen(true)}
        >
          <CardContent className="flex flex-col items-center justify-center h-full p-4 text-center">
            <Plus className="h-8 w-8 text-primary mb-2" />
            <div className="font-semibold text-md">创建新应用</div>
          </CardContent>
        </Card>

        {/* 应用卡片列表 */}
        {filteredApps.map((app) => (
          <Card
            key={app.id}
            className="group min-h-[158px] hover:shadow-md transition-shadow cursor-pointer"
            onClick={() => handleAppClick(app.id)}
          >
            <CardContent className="h-full pt-4 pb-2 px-3">
              <div className="flex flex-col justify-between h-full">
                {/* 应用信息 */}
                <div className="flex items-start space-x-3">
                  {/* 应用图标 */}
                  <div className="flex items-center">
                    <div className="flex items-center justify-center w-9 h-9 bg-gradient-to-r from-blue-500 to-indigo-600 rounded-lg">
                      <Zap className="text-white w-6 h-6" />
                    </div>
                  </div>
                  <div>
                    <div className="font-semibold text-sm truncate">{app.name}</div>
                    <div className="flex items-center gap-1 text-[10px] font-medium leading-[18px] text-muted-foreground">
                      <div className="truncate">xxx</div>
                      <div>·</div>
                      <div className="truncate">编辑于 2025/08/13</div>
                    </div>
                  </div>
                </div>

                {/* 应用信息 */}
                <div className="flex-1 mt-3">
                  <p className="text-xs text-muted-foreground line-clamp-2">{app.description}</p>
                </div>

                {/* 标签 */}
                <div className="flex justify-between items-center h-[36px]">
                  <div className="flex-1 flex flex-wrap items-center gap-1">
                    <Tag className="h-4 w-4 mr-1 text-muted-foreground" />
                    <span className="text-sm text-muted-foreground">{app.tags.join(", ")}</span>
                  </div>
                  <div className="hidden group-hover:block">
                    <Button variant="ghost" className="h-9 w-9">
                      <Ellipsis className="h-4 w-4" />
                    </Button>
                  </div>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      <CreateNewApplicationDialog
        open={isCreateNewApplicationDialogOpen}
        onOpenChange={setIsCreateNewApplicationDialogOpen}
      />
    </div>
  )
}

export default AppsPage
